package com.ronsai.umtrack.util;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.UUID;

/**
 * 手机唯一标识生成工具
 */
public class UUIDS {

    private Context mContext;
    private static UUIDS device;
    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    private final static String DEFAULT_FILE_NAME = ".ronsai_uuid";
    private final static String FILE_ANDROID = Environment.getExternalStoragePublicDirectory("Android") + File.separator + DEFAULT_FILE_NAME;
    private final static String FILE_DCIM = Environment.getExternalStoragePublicDirectory("DCIM") + File.separator + DEFAULT_FILE_NAME;

    private UUIDS(Context context) {
        mContext = context;
    }

    public static UUIDS buildeID(Context context) {
        if (device == null) {
            synchronized (UUIDS.class) {
                if (device == null) {
                    device = new UUIDS(context);
                }
            }
        }
        return device;
    }

    /**
     * 获取唯一标识。
     */
    public String getDeviceId() {
        check();
        SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        return prefs.getString(PREFS_DEVICE_ID, null);
    }

    /**
     * 清除deviceId
     */
    public void deleteDeviceId() {
        SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PREFS_DEVICE_ID, null);
        editor.apply();
        File androidFile = new File(FILE_ANDROID);
        File dcimFile = new File(FILE_DCIM);
        if (androidFile.exists()) androidFile.delete();
        if (dcimFile.exists()) dcimFile.delete();
    }

    /**
     * 生成唯一标识
     * 策略：以ANDROID_ID为基础，在获取失败时以TelephonyManager.getDeviceId()为备选方法，如果再失败，使用UUID的生成。
     */
    private String createDeviceId() {
        String deviceId = null;
        String androidId = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
        // 1、ANDROID_ID
        if (!"9774d56d682e549c".equals(androidId)) {
            deviceId = androidId;
        }
        // 2、TelephonyManager.getDeviceId()
        if (deviceId == null) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                deviceId = ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            }
        }
        // 3、UUID.randomUUID()
        if (deviceId == null) {
            deviceId = UUID.randomUUID().toString().replace("-", "");
        }
        return deviceId;
    }

    /**
     * 检测唯一标识是否被清除
     */
    public void check() {
        // 检测SharedPreferences的deviceId是否为空
        SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        String deviceId = prefs.getString(PREFS_DEVICE_ID, null);
        if (deviceId == null) {
            // 检测SD卡的deviceId是否为空
            String androidFileId = checkDeviceIdWithFile(FILE_ANDROID);
            String dcimFileId = checkDeviceIdWithFile(FILE_DCIM);

            if (androidFileId == null && dcimFileId == null) {
                // 获取唯一标识deviceId
                deviceId = createDeviceId();
                saveDeviceIdWithSP(deviceId);
                saveDeviceIdWithFile(deviceId, FILE_ANDROID);
                saveDeviceIdWithFile(deviceId, FILE_DCIM);
            } else if (androidFileId == null) {
                // /Android目录下的存储deviceId文件被删除
                saveDeviceIdWithSP(dcimFileId);
                saveDeviceIdWithFile(dcimFileId, FILE_ANDROID);
            } else if (dcimFileId == null) {
                // /DCIM目录下的存储deviceId文件被删除
                saveDeviceIdWithSP(androidFileId);
                saveDeviceIdWithFile(androidFileId, FILE_DCIM);
            } else {
                // SharedPreferences保存的deviceId被清除
                saveDeviceIdWithSP(androidFileId);
            }
        } else {
            // 检测保存的文件是否被删除
            if (checkDeviceIdWithFile(FILE_ANDROID) == null) {
                saveDeviceIdWithFile(deviceId, FILE_ANDROID);
            }
            if (checkDeviceIdWithFile(FILE_DCIM) == null) {
                saveDeviceIdWithFile(deviceId, FILE_DCIM);
            }
        }
    }

    /**
     * 检测文件中的deviceId
     */
    private String checkDeviceIdWithFile(String path) {
        BufferedReader reader = null;
        try {
            File file = new File(path);
            reader = new BufferedReader(new FileReader(file));
            return reader.readLine();
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存deviceId到文件
     */
    private void saveDeviceIdWithFile(String deviceId, String path) {
        try {
            File file = new File(path);
            FileWriter writer = new FileWriter(file);
            writer.write(deviceId);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存deviceId到SP文件
     */
    private void saveDeviceIdWithSP(String deviceId) {
        SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PREFS_DEVICE_ID, deviceId);
        editor.apply();
    }

}
